<template>
  <div class="chart-container">
    <canvas id="chart"></canvas>
  </div>
</template>

<script>
import { onMounted, ref, defineComponent } from "vue";
import {
  Chart,
  CategoryScale,
  LinearScale,
  LineElement,
  PointElement,
  LineController,  // 添加 LineController
  Title,
  Tooltip,
  Legend
} from "chart.js";

// 注册 Chart.js 所需的组件
Chart.register(
    CategoryScale,
    LinearScale,
    LineElement,
    PointElement,
    LineController,  // 注册 LineController
    Title,
    Tooltip,
    Legend
);

export default defineComponent({
  name: 'ChartComponent',
  setup() {
    const dates = ref([]);
    const prices = ref([]);

    onMounted(async () => {
      try {
        dates.value = ['2024-01', '2024-02', '2024-03', '2024-04', '2024-06','2024-05','2024-07','2024-08','2024-09','2024-10','2024-11','2024-12','2024-13','2024-14','2024-15','2024-16','2024-17','2024-18','2024-19','2024-20'];
        prices.value = [100, 120, 115, 130, 125,130,110,90,100,105,120,130,135,130,125,140,160,145,135,160];

        const ctx = document.getElementById("chart");  // 移除 .getContext("2d")

        new Chart(ctx, {
          type: "line",
          data: {
            labels: dates.value,
            datasets: [
              {
                label: "股票價格",
                data: prices.value,
                borderColor: "rgba(75, 192, 192, 1)",
                backgroundColor: "rgba(75, 192, 192, 0.2)",
                borderWidth: 2,
                tension: 0.4,
                fill: true,
                pointRadius: 4,
                pointBackgroundColor: "rgba(75, 192, 192, 1)",
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                position: "top",
              },
              title: {
                display: true,
                text: "股票價格走勢圖"
              }
            },
            scales: {
              x: {
                title: {
                  display: true,
                  text: "日期",
                },
                grid: {
                  display: true,
                  drawBorder: true,
                },
              },
              y: {
                title: {
                  display: true,
                  text: "股價",
                },
                ticks: {
                  beginAtZero: false,
                },
                grid: {
                  display: true,
                  drawBorder: true,
                },
              },
            },
          },
        });
      } catch (error) {
        console.error('圖表渲染失敗:', error);
      }
    });

    return {
      dates,
      prices
    };
  }
});
</script>

<style scoped>
.chart-container {
  position: relative;
  width: 100%;
  height: 400px;
  padding: 20px;
}

canvas {
  width: 100% !important;
  height: 100% !important;
}
</style>